package pri.damai.xiaowu.anydoor.util;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import pri.damai.xiaowu.anydoor.business.BaseModel;
import pri.damai.xiaowu.anydoor.netty.HandlerHolder;

/**
 * 基础编解码工具类
 *
 * @description
 * @author YangXinFu
 * @date 13:42 2022/8/8
 **/
public class BizCodecUtils {

    public static BaseModel decode(ByteBuf byteBuf) throws Exception {
        //1.根据协议取出数据
        int tag = byteBuf.readInt();//标识符
        byte code = byteBuf.readByte();//获取指令
        int len = byteBuf.readInt();//获取数据长度
        byte[] bytes = new byte[len];
        byteBuf.readBytes(bytes);

        //2.根据code获取类型
        Class<? extends BaseModel> c = HandlerHolder.getModelClass(code);

        //3.反序列化
        return JSON.parseObject(bytes, c);
    }

    public static void encode(BaseModel baseModel, ByteBuf byteBuf) throws Exception {
        //1.把实体序列化成字节数字
        byte[] bytes = JSON.toJSONBytes(baseModel);

        //2.根据协议组装数据
        byteBuf.writeInt(baseModel.tag());//标识（4个字节）
        byteBuf.writeByte(baseModel.code());//指令（1个字节）
        byteBuf.writeInt(bytes.length);//长度（4个字节）
        byteBuf.writeBytes(bytes);// 内容
    }

}
